package com.sunwayhorizo.health.business.patad.encounter.query;

import java.util.*;

import javax.ejb.*;
import javax.persistence.*;
import org.jboss.seam.annotations.*;
import com.sunwayhorizo.health.business.base.query.*;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.*;
import com.sunwayhorizo.health.hl7.persistent.*;
import com.sunwayhorizo.health.hl7.rim.*;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.vocabulary.*;

@Name("PatientEncounterQuery")
@Stateless
public class PatientEncounterQuery extends BaseQuery implements PatientEncounterQueryLocal
{
    private Map<String, Map<String, Object>> conditions = new HashMap<String, Map<String, Object>>();


    @Override
    // 根据动作ii查询活的入院动作
    public PatientEncounter findActiveInhosActByII(String ii) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", ii);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        enc.put("codeEtsId", ActCode.HOSPITALIZED.code().stringValue());
        conditions.put("enc", enc);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActiveInhosActByII-无入院动作");
            return null;
        }

    }


    @Override
    // 根据动作ii查询最近一次入院动作
    public PatientEncounter findLastInhosActByEncounterId(String encounterId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.HOSPITALIZED.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActiveInhosActByII-无入院动作");
            return null;
        }

    }


    @Override
    // 根据患者roleii查询最近一次患者的入院的动作
    public PatientEncounter findLastInhosActByPatientNatureId(String id) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.PATIENTID.toString());
        rii.put("extensionTxt", id);
        conditions.put("rii", rii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.HOSPITALIZED.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findLastInhosActByPatientNatureId-无入院动作");
            return null;
        }

    }


    @Override
    // 根据动作ii查询活的入科动作
    public PatientEncounter findActiveIndepartmentActByII(String encounterId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActiveIndepartmentActByII-无入科动作");
            return null;
        }
    }


    @Override
    // 查询患者当前活的转科信息
    public PatientEncounter findTransferPatientEncounter(String patientNatureId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.PATIENTID.toString());
        rii.put("extensionTxt", patientNatureId);
        conditions.put("rii", rii);

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.PATIENTTRANSFER.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findTransferPatientEncounter-无转科动作");
            return null;
        }

    }


    @Override
    // 查询患者当前活的出院信息
    public PatientEncounter findOutPatientEncounter(String natureId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.PATIENTID.toString());
        rii.put("extensionTxt", natureId);
        conditions.put("rii", rii);

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.DISCHARGED.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findTransferPatientEncounter-无转科动作");
            return null;
        }

    }


    @Override
    // 查询患者最近一次入科信息
    public PatientEncounter findLastIndepartmentByHosNo(String hospitalNo) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.ADMISSIONNO.toString());
        rii.put("extensionTxt", hospitalNo);
        conditions.put("rii", rii);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findLastIndepartmentByHosNo-根据病案号查不到" + hospitalNo + "入科动作");
            return null;
        }
    }


    @Override
    // 查询患者当前活的入科信息
    public PatientEncounter findLastAvtiveIndepartmentPatientEncounter(String patientNatureId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.PATIENTID.toString());
        rii.put("extensionTxt", patientNatureId);
        conditions.put("rii", rii);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findLastAvtiveIndepartmentPatientEncounter-无入科动作");
            return null;
        }
    }


    @Override
    // 查询患者当前活的入接诊信息
    public PatientEncounter findLastAvtiveRecievingPatientEncounter(String patientNatureId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.PATIENTID.toString());
        rii.put("extensionTxt", patientNatureId);
        conditions.put("rii", rii);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findLastAvtiveRecievingPatientEncounter-无接诊动作");
            return null;
        }
    }


    @Override
    // 根绝病历状态、接诊医生查询接诊动作
    public List<PatientEncounter> findPatientEncountersByDoctorRoleIdAndStatusCode(String roleId, List<String> statusCode, int pageNo, int pageSize)
        throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        // enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> p = new HashMap<String, Object>();
        p.put("typeCode", ParticipationType.ESC.code().stringValue());
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("roleId", Long.parseLong(roleId));
        conditions.put("r", r);

        Map<String, Object> sr = new HashMap<String, Object>();
        sr.put("splitCode<>", ActRelationshipSplit.E1.code().stringValue());
        conditions.put("sr", sr);

        Map<String, Object> ta = new HashMap<String, Object>();
        ta.put("classCode", ActClass.DOC.code().stringValue());
        ta.put("statusCode", statusCode);
        conditions.put("ta", ta);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, pageNo, pageSize);
        return encs;
    }


    // 根据患者姓名查询我的患者
    @Override
    public List<PatientEncounter> findPatientEncountersByDoctorRoleIdAndStatusCode(String roleId, List<String> statusCode, int pageNo, int pageSize,
        String patientName)
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append("select enc from Patient pat left join pat.rolePrtcptnsList rp left join rp.participationAct enc left join enc.prtcptnsActList part ");
        jpql.append(" left join part.roleParticipation role left join enc.sourceActRelationsList sr left join sr.targetAct ta ");
        jpql.append(" left join pat.playerEntities pe left join pe.entyNamesList en left join en.entyNameUsesList enu ");
        jpql.append(" where ta.classCode=");
        jpql.append(convertInJpql(ActClass.DOC.code().stringValue()));
        jpql.append(" where ta.statusCode in ");
        jpql.append(convertInJpql(statusCode));
        jpql.append(" and enc.codeEtsId=");
        jpql.append(convertInJpql(ActCode.RECEIVING.code().stringValue()));
        jpql.append(" and role.roleId=");
        jpql.append(Long.parseLong(roleId));
        jpql.append(" and part.typeCode=");
        jpql.append(convertInJpql(ParticipationType.ESC.code().stringValue()));
        jpql.append(" and part.splitCode not in");
        jpql.append(convertInJpql(ActRelationshipSplit.E1.code().stringValue()));
        jpql.append(" and en.formatted=");
        jpql.append(convertInJpql(patientName));
        jpql.append(" and enu.use=");
        jpql.append(convertInJpql(EntityNameUse.L.code().stringValue()));
        @SuppressWarnings("unchecked")
        List<PatientEncounter> pes = em.createQuery(jpql.toString()).setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize).getResultList();
        if (pes.isEmpty())
        {
            log.info("PatientEncounterQuery-findPatientEncountersByDoctorRoleIdAndStatusCode-查不到患者！");
            return null;
        }
        else
        {
            return pes;
        }

    }


    // 根据患者姓名查询我的患者总数
    @Override
    public long findCountMyPatients(String roleId, List<String> statusCode,  String patientName)
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append("select count(distinct enc.actId) from Patient pat left join pat.rolePrtcptnsList rp left join rp.participationAct enc left join enc.prtcptnsActList part ");
        jpql.append(" left join part.roleParticipation role left join enc.sourceActRelationsList sr left join sr.targetAct ta ");
        jpql.append(" left join pat.playerEntities pe left join pe.entyNamesList en left join en.entyNameUsesList enu ");
        jpql.append(" where ta.classCode=");
        jpql.append(convertInJpql(ActClass.DOC.code().stringValue()));
        jpql.append(" where ta.statusCode in ");
        jpql.append(convertInJpql(statusCode));
        jpql.append(" and enc.codeEtsId=");
        jpql.append(convertInJpql(ActCode.RECEIVING.code().stringValue()));
        jpql.append(" and role.roleId=");
        jpql.append(Long.parseLong(roleId));
        jpql.append(" and part.typeCode=");
        jpql.append(convertInJpql(ParticipationType.ESC.code().stringValue()));
        jpql.append(" and part.splitCode not in");
        jpql.append(convertInJpql(ActRelationshipSplit.E1.code().stringValue()));
        jpql.append(" and en.formatted=");
        jpql.append(convertInJpql(patientName));
        jpql.append(" and enu.use=");
        jpql.append(convertInJpql(EntityNameUse.L.code().stringValue()));
        @SuppressWarnings("unchecked")
        Long count = (Long) em.createQuery(jpql.toString()).getResultList().get(0);

        return count;
    }


    public long findMyPatientsByDoctorCount(String roleId, List<String> statusCode) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        // enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> p = new HashMap<String, Object>();
        p.put("typeCode", ParticipationType.ESC.code().stringValue());
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("roleId", Long.parseLong(roleId));
        conditions.put("r", r);

        Map<String, Object> sr = new HashMap<String, Object>();

        conditions.put("sr", sr);

        Map<String, Object> ta = new HashMap<String, Object>();
        ta.put("classCode", ActClass.DOC.code().stringValue());
        ta.put("statusCode", statusCode);
        conditions.put("ta", ta);

        return baseCountEncounterQuery(conditions);
    }


    @Override
    public long findMyPatientInGroup(String workGroupRoleId, List<String> statusCode) throws Hl7Exception
    {

        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        // enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("classCode", RoleClass.EMP.code().stringValue());
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        p.put("typeCode", ParticipationType.ESC.code().stringValue());
        conditions.put("p", p);

        Map<String, Object> sr = new HashMap<String, Object>();
        sr.put("splitCode<>", ActRelationshipSplit.E1.code().stringValue());
        conditions.put("sr", sr);

        Map<String, Object> ta = new HashMap<String, Object>();
        ta.put("classCode", ActClass.DOC.code().stringValue());
        ta.put("statusCode", statusCode);
        conditions.put("ta", ta);

        Map<String, Object> tre = new HashMap<String, Object>();
        conditions.put("tre", tre);

        Map<String, Object> sa = new HashMap<String, Object>();
        conditions.put("sa", sa);

        Map<String, Object> p2 = new HashMap<String, Object>();
        conditions.put("p2", p2);

        Map<String, Object> r2 = new HashMap<String, Object>();
        conditions.put("r2", r2);

        Map<String, Object> se2 = new HashMap<String, Object>();
        conditions.put("se2", se2);

        Map<String, Object> pr3 = new HashMap<String, Object>();
        pr3.put("roleId", Long.parseLong(workGroupRoleId));
        conditions.put("pr3", pr3);

        return baseCountEncounterQuery(conditions);

    }


    @Override
    // 根绝病历状态、工作组查询接诊动作
    public List<PatientEncounter> findPatientEncountersByWorkgroupIdsAndStatusCode(String workGroupRoleId, List<String> statusCode, int pageNo,
        int pageSize) throws Hl7Exception
    {

        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        // enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("classCode", RoleClass.EMP.code().stringValue());
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        p.put("typeCode", ParticipationType.ESC.code().stringValue());
        conditions.put("p", p);

        Map<String, Object> sr = new HashMap<String, Object>();
        sr.put("splitCode<>", ActRelationshipSplit.E1.code().stringValue());
        conditions.put("sr", sr);

        Map<String, Object> ta = new HashMap<String, Object>();
        ta.put("classCode", ActClass.DOC.code().stringValue());
        ta.put("statusCode", statusCode);
        conditions.put("ta", ta);

        Map<String, Object> tre = new HashMap<String, Object>();
        conditions.put("tre", tre);

        Map<String, Object> sa = new HashMap<String, Object>();
        conditions.put("sa", sa);

        Map<String, Object> p2 = new HashMap<String, Object>();
        conditions.put("p2", p2);

        Map<String, Object> r2 = new HashMap<String, Object>();
        conditions.put("r2", r2);

        Map<String, Object> se2 = new HashMap<String, Object>();
        conditions.put("se2", se2);

        Map<String, Object> pr3 = new HashMap<String, Object>();
        pr3.put("roleId", Long.parseLong(workGroupRoleId));
        conditions.put("pr3", pr3);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, pageNo, pageSize);
        return encs;

    }


    //
    @Override
    public RimCoreActPrtcptns findRecieveingEncounterById(String id)
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append("select prt from PatientEncounter act left join act.actsIiList ii left join act.prtcptnsActList prt ");
        jpql.append("  where ii.clinicNo='");
        jpql.append(id);
        jpql.append("' and act.codeEtsId ='");
        jpql.append(ActCode.RECEIVING.code().stringValue());
        jpql.append("' and prt.typeCode='ADM' ");
        jpql.append(" and prt.roleParticipation.codeEtsId='EMPLOYEEROLE'");

        @SuppressWarnings("unchecked")
        List<RimCoreActPrtcptns> prts = em.createQuery(jpql.toString()).getResultList();
        if (!prts.isEmpty())
        {
            return prts.get(0);
        }
        log.info("PatientEncounterDaoJPQL-findRecieveingEncounterById-未找到相关接诊动作");
        return null;
    }


    //
    @Override
    public long findInhostNumByNatureId(String natureId)
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append("select prt.sequenceNum from PatientEncounter act left join act.actsIiList ii left join act.prtcptnsActList prt left join prt.roleParticipation r left join r.roleIiList rii ");
        jpql.append("  where rii.extensionTxt='");
        jpql.append(natureId);
        jpql.append("' and act.codeEtsId ='");
        jpql.append(ActCode.HOSPITALIZED.code().stringValue());
        jpql.append("' and prt.typeCode='SBJ' ");
        jpql.append(" order by act.activityEndDateTs desc ");
        @SuppressWarnings("unchecked")
        List<Long> prts = em.createQuery(jpql.toString()).setFirstResult(0).setMaxResults(1).getResultList();
        if (!prts.isEmpty())
        {
            return prts.get(0);
        }
        log.info("PatientEncounterDaoJPQL-findRecieveingEncounterById-未找到相关接诊动作");
        return 0;
    }


    // 根据actii查询活的接诊
    @Override
    public PatientEncounter findActiveRecieveingEncounterById(String id) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", id);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findLastAvtiveRecievingPatientEncounter-无接诊动作");
            return null;
        }
    }


    // 查询所有活的接诊
    @Override
    public List<PatientEncounter> findAllActiveRecieveing() throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 0, 0);
        return encs;
    }


    // 上次已完成转科
    @Override
    public PatientEncounter findLastCompleteTransferPatientEncounter(String encounterId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.PATIENTTRANSFER.code().stringValue());
        enc.put("statusCode", ActStatus.COMPLETED.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActiveIndepartmentActByII-无入科动作");
            return null;
        }

    }


    // 查询入院待入科列表
    @Override
    public List<PatientEncounter> findAllActiveInhospital(String workgroupId, int pageNo, int pageSize) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.HOSPITALIZED.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();

        r.put("roleId", Long.parseLong(workgroupId));
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, pageNo, pageSize);
        return encs;
    }


    // 查询入院待入科列表(患者名称)
    @Override
    public List<PatientEncounter> findAllActiveInhospital(String workgroupId, int pageNo, int pageSize, String patientName) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();

        jpql.append("select distinct enc from Patient patient left join patient.rolePrtcptnsList p left join p.participationAct enc left join enc.prtcptnsActList p2 left join p2.roleParticipation r  ");
        jpql.append(" left join patient.playerEntities pe ");
        jpql.append(" left join pe.entyNamesList en ");
        jpql.append(" where r.roleId=");
        jpql.append(Long.parseLong(workgroupId));
        jpql.append(" and enc.codeEtsId=");
        jpql.append(convertInJpql(ActCode.HOSPITALIZED.code().stringValue()));
        jpql.append(" and enc.statusCode=");
        jpql.append(convertInJpql(ActStatus.ACTIVE.code().stringValue()));
        jpql.append(" and en.formatted like ");
        jpql.append(convertInJpql(patientName + "%"));
        log.info("PatientEncounterQuery-findAllActiveInhospital-" + jpql);
        @SuppressWarnings("unchecked")
        List<PatientEncounter> encs = em.createQuery(jpql.toString()).setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize).getResultList();
        return encs;

    }


    // 查询入院待入科列表(患者名称)
    @Override
    public long findCountAllActiveInhospital(String workgroupId, int pageNo, int pageSize, String patientName) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();

        jpql.append("select count (distinct enc.actId) from Patient patient left join patient.rolePrtcptnsList p left join p.participationAct enc left join enc.prtcptnsActList p2 left join p2.roleParticipation r  ");
        jpql.append(" left join patient.playerEntities pe ");
        jpql.append(" left join pe.entyNamesList en ");
        jpql.append(" where r.roleId=");
        jpql.append(Long.parseLong(workgroupId));
        jpql.append(" and enc.codeEtsId=");
        jpql.append(convertInJpql(ActCode.HOSPITALIZED.code().stringValue()));
        jpql.append(" and enc.statusCode=");
        jpql.append(convertInJpql(ActStatus.ACTIVE.code().stringValue()));
        jpql.append(" and en.formatted like ");
        jpql.append(convertInJpql(patientName + "%"));
        log.info("PatientEncounterQuery-findAllActiveInhospital-" + jpql);

        Long count = (Long) em.createQuery(jpql.toString()).getResultList().get(0);
        return count;

    }


    @Override
    public long findCountAllActiveInhospital(String workgroupId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.HOSPITALIZED.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();

        r.put("roleId", Long.parseLong(workgroupId));
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        return baseCountEncounterQuery(conditions);

    }


    // 查询入院待入科列表
    @Override
    public List<PatientEncounter> findAllActiveTransfer(String workgroupId, int pageNo, int pageSize) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.PATIENTTRANSFER.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("roleId", Long.parseLong(workgroupId));
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, pageNo, pageSize);
        return encs;
    }


    @Override
    public long findCountAllActiveTransfer(String workgroupId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.PATIENTTRANSFER.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> se = new HashMap<String, Object>();
        conditions.put("se", se);

        Map<String, Object> pr = new HashMap<String, Object>();
        pr.put("roleId", Long.parseLong(workgroupId));
        conditions.put("pr", pr);

        return baseCountEncounterQuery(conditions);

    }


    // 根据workgroupRoleId查询待接诊列表
    @Override
    public List<PatientEncounter> findAllActiveIndepartments(String workgroupId, int pageNo, int pageSize) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> sreIsEmpty = new HashMap<String, Object>();
        conditions.put("sre is empty", sreIsEmpty);

        Map<String, Object> se = new HashMap<String, Object>();
        conditions.put("se", se);

        Map<String, Object> pr = new HashMap<String, Object>();
        pr.put("roleId", Long.parseLong(workgroupId));
        conditions.put("pr", pr);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, pageNo, pageSize);
        return encs;
    }


    @Override
    public long findAllActiveIndepartmentsCount(String workgroupId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> sreIsEmpty = new HashMap<String, Object>();
        conditions.put("sre is empty", sreIsEmpty);

        Map<String, Object> se = new HashMap<String, Object>();
        conditions.put("se", se);

        Map<String, Object> pr = new HashMap<String, Object>();
        pr.put("roleId", Long.parseLong(workgroupId));
        conditions.put("pr", pr);

        return baseCountEncounterQuery(conditions);

    }


    // 查询当前工作组（entityId）转科列表
    @Override
    public List<PatientEncounter> findIndepartment(String workgroupId, int pageNo, int pageSize) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("codeEtsId", RoleCode.BED.code().stringValue());
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> se = new HashMap<String, Object>();
        se.put("entityId", Long.parseLong(workgroupId));
        conditions.put("se", se);

        // Map<String, Object> pr = new HashMap<String, Object>();
        // pr.put("roleId", Long.parseLong(workgroupId));
        // conditions.put("pr", pr);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, pageNo, pageSize);
        return encs;
    }


    // 上次完成入科
    @Override
    public PatientEncounter findLastCompleteIndepartment(String encounterId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());
        enc.put("statusCode", ActStatus.COMPLETED.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActiveIndepartmentActByII-无入科动作");
            return null;
        }

    }


    // 上次入科
    @Override
    public PatientEncounter findLastIndepartment(String encounterId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());

        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActiveIndepartmentActByII-无入科动作");
            return null;
        }

    }


    // 上次完成接诊
    @Override
    public PatientEncounter findLastCompleteRecieving(String encounterId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        enc.put("statusCode", ActStatus.COMPLETED.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActiveIndepartmentActByII-无入科动作");
            return null;
        }

    }


    // 根据actii查询上次活的转科
    @Override
    public PatientEncounter findLastActiveTransfer(String encounterId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.PATIENTTRANSFER.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActiveIndepartmentActByII-无入科动作");
            return null;
        }

    }


    // 根据就诊号查询所有活的PatientEncounter
    @Override
    public List<PatientEncounter> findAllActivePE(String encounterId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 0, 0);

        return encs;
    }


    // 根据患者id查询所有活的PatientEncounter
    @Override
    public List<PatientEncounter> findAllActivePEByPatientId(String natureId) throws Hl7Exception
    {

        conditions.clear();

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.PATIENTID.toString());
        rii.put("extensionTxt", natureId);
        conditions.put("rii", rii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 0, 0);
        return encs;
    }


    @SuppressWarnings("unchecked")
    public List<PatientEncounter> findInPatientByWorkGroupId(String workGroupId, int pageNo, int pageSize) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", "INDEPARTMENT");
        enc.put("statusCode", "active");
        conditions.put("act", enc);

        Map<String, Object> part = new HashMap<String, Object>();
        part.put("typeCode", ParticipationType.ELOC.code().toString());
        conditions.put("part", part);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("codeEtsId", RoleCode.BED.code().toString());
        conditions.put("r", r);

        Map<String, Object> scopeEnty = new HashMap<String, Object>();
        conditions.put("scopeEnty", scopeEnty);

        Map<String, Object> playRole = new HashMap<String, Object>();
        playRole.put("roleId", workGroupId);
        conditions.put("playRole", playRole);

        List<PatientEncounter> encs = (List<PatientEncounter>) queryResults(conditions, PatientEncounter.class, pageNo, pageSize);
        return encs;
    }


    public Long findCountInPatientByWorkGroupId(String workGroupId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", "INDEPARTMENT");
        enc.put("statusCode", "active");
        conditions.put("act", enc);

        Map<String, Object> part = new HashMap<String, Object>();
        part.put("typeCode", ParticipationType.ELOC.code().toString());
        conditions.put("part", part);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("codeEtsId", RoleCode.BED.code().toString());
        conditions.put("r", r);

        Map<String, Object> scopeEnty = new HashMap<String, Object>();
        conditions.put("scopeEnty", scopeEnty);

        Map<String, Object> playRole = new HashMap<String, Object>();
        playRole.put("roleId", workGroupId);
        conditions.put("playRole", playRole);

        Long count = (Long) queryCountResults(conditions, PatientEncounter.class);
        return count;
    }


    private Query getBaseEncounterQuery(Map<String, Map<String, Object>> conditions, int pageNo, int pageSize)
    {
        Query query = em.createQuery(getBaseEncounterQueryJpql(conditions, null));
        if (pageNo > 0 && pageSize > 0)
        {
            query.setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize);
        }
        return query;
    }


    @Override
    public List<PatientEncounter> baseEncounterQuery(Map<String, Map<String, Object>> conditions, int pageNo, int pageSize) throws Hl7Exception
    {
        Query query = em.createQuery(getBaseEncounterQueryJpql(conditions, null));
        if (pageNo > 0 && pageSize > 0)
        {
            query.setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize);
        }
        @SuppressWarnings("unchecked")
        List<PatientEncounter> encounters = query.getResultList();
        return encounters;
    }


    @Override
    public long baseCountEncounterQuery(Map<String, Map<String, Object>> conditions) throws Hl7Exception
    {
        Query query = em.createQuery(getBaseEncounterQueryJpql(conditions, Long.class));
        Long count = (Long) query.getSingleResult();
        return count;
    }


    @Override
    public <T> List<T> getObjects(Class<T> clazz, Map<String, Object> conditions) throws Hl7Exception
    {

        return super.getObjects(clazz, conditions);
    }


    // 根据接诊患者roleId查询活的接诊动作
    @Override
    public PatientEncounter findRecieveingEncounterByPatientRoleId(String roleId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("roleId", roleId);
        conditions.put("r", r);
        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);

        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findRecieveingEncounterByPatientRoleId-无接诊动作");
            return null;
        }
    }


    // 根据床号及工作组角色id查询入科动作
    @Override
    public List<PatientEncounter> findPatientByBedNoAndWorkgroupId(String bedNo, String workgroupRoleId) throws Hl7Exception
    {

        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> pe = new HashMap<String, Object>();
        conditions.put("pe", pe);

        Map<String, Object> en = new HashMap<String, Object>();
        en.put("formatted", bedNo);
        conditions.put("en", en);

        Map<String, Object> enu = new HashMap<String, Object>();
        enu.put("use", EntityNameUse.L.toString());
        conditions.put("enu", enu);

        Map<String, Object> pr = new HashMap<String, Object>();
        pr.put("roleId", workgroupRoleId);
        conditions.put("pr", pr);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 0, 0);
        return encs;
    }


    @Override
    public long findCountIndepartment(String workgroupId) throws Hl7Exception
    {

        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();

        enc.put("codeEtsId", ActCode.INDEPARTMENT.code().stringValue());
        enc.put("statusCode", ActStatus.ACTIVE.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("codeEtsId", RoleCode.BED.code().stringValue());
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> se = new HashMap<String, Object>();
        se.put("entityId", Long.parseLong(workgroupId));
        conditions.put("se", se);

        // Map<String, Object> pr = new HashMap<String, Object>();
        // pr.put("roleId", Long.parseLong(workgroupId));
        // conditions.put("pr", pr);

        return baseCountEncounterQuery(conditions);
    }


    @Override
    public List<PatientEncounter> findAllReceivingByPatientId(String patientId) throws Hl7Exception
    {

        conditions.clear();

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.ADMISSIONNO.toString());
        rii.put("extensionTxt", patientId);
        conditions.put("rii", rii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 0, 0);

        return encs;
    }


    @Override
    public PatientEncounter findLastReceving(String patientId) throws Hl7Exception
    {

        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("roleId", Long.parseLong(patientId));
        conditions.put("r", r);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findLastAvtiveRecievingPatientEncounter-无接诊动作");
            return null;
        }
    }


    @Override
    public PatientEncounter findLastRecevingById(String encounterId) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());

        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActiveIndepartmentActByII-无入科动作");
            return null;
        }
    }


    // 查询上次被移除
    @Override
    public PatientEncounter findLastRemoved(String patientId) throws Hl7Exception
    {

        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("roleId", Long.parseLong(patientId));
        conditions.put("r", r);

        Map<String, Object> sr = new HashMap<String, Object>();
        sr.put("splitCode", ActRelationshipSplit.E1.code().stringValue());
        conditions.put("sr", sr);

        Map<String, Object> ta = new HashMap<String, Object>();
        conditions.put("ta", ta);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findLastAvtiveRecievingPatientEncounter-无接诊动作");
            return null;
        }
    }


    @Override
    public PatientEncounter findLastRecevingByRoleId(String roleId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.RECEIVING.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("roleId", Long.parseLong(roleId));
        conditions.put("r", r);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findLastAvtiveRecievingPatientEncounter-无接诊动作");
            return null;
        }
    }


    @Override
    public PatientEncounter findInhosBytime(Date admission_time, String patientId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.HOSPITALIZED.code().stringValue());
        enc.put("activityStartDateTs", admission_time);
        conditions.put("enc", enc);

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.PATIENTID.toString());
        rii.put("extensionTxt", patientId);
        conditions.put("rii", rii);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Query query = getBaseEncounterQuery(conditions, 1, 1);
        query.setParameter("activityStartDateTs", admission_time, TemporalType.TIMESTAMP);
        @SuppressWarnings("unchecked")
        List<PatientEncounter> encs = query.getResultList();
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findInhosBytime-无入院动作");
            return null;
        }

    }


    @Override
    public PatientEncounter findLastInHosActByPatientRoleId(String roleId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.HOSPITALIZED.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("roleId", Long.parseLong(roleId));
        conditions.put("r", r);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findLastInHospitalByRoleId-无入院动作");
            return null;
        }
    }


    @Override
    public PatientEncounter findLastAvtiveOutHos(String natureId) throws Hl7Exception
    {
        conditions.clear();

        Map<String, Object> r = new HashMap<String, Object>();
        conditions.put("r", r);

        Map<String, Object> p = new HashMap<String, Object>();
        conditions.put("p", p);

        Map<String, Object> rii = new HashMap<String, Object>();
        rii.put("identifierName", RoleIICode.PATIENTID.toString());
        rii.put("extensionTxt", natureId);
        conditions.put("rii", rii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", ActCode.DISCHARGED.code().stringValue());
        conditions.put("enc", enc);

        Map<String, Object> orderBy = new HashMap<String, Object>();
        orderBy.put("desc", "enc.activityEndDateTs");
        conditions.put("order by", orderBy);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 1, 1);
        if (encs.isEmpty())
        {
            log.info("上次活的出院动作为空！");
            return null;
        }
        return encs.get(0);
    }


    @Override
    // 根据动作ii查询某一次动作
    public PatientEncounter findActByEncounterIdAndNumAndActCode(String encounterId, String encounterNum, String actCodeString) throws Hl7Exception
    {
        conditions.clear();
        Map<String, Object> aii = new HashMap<String, Object>();
        aii.put("clinicNo", encounterId);
        conditions.put("aii", aii);

        Map<String, Object> enc = new HashMap<String, Object>();
        enc.put("codeEtsId", actCodeString);
        conditions.put("enc", enc);

        Map<String, Object> p = new HashMap<String, Object>();
        if (StrUtil.isEmpty(encounterNum))
        {
            encounterNum = "1";
        }
        p.put("sequenceNum", encounterNum);
        conditions.put("p", p);

        Map<String, Object> r = new HashMap<String, Object>();
        r.put("codeEtsId", RoleCode.PATIENT.code().stringValue());
        conditions.put("r", r);

        List<PatientEncounter> encs = baseEncounterQuery(conditions, 0, 0);
        if (!encs.isEmpty())
        {
            return encs.get(0);
        }
        else
        {
            log.info("PatientEncounterQuery-findActByEncounterIdAndNumAndActCode-无动作");
            return null;
        }
    }


    @Override
    public Role findBedRoleByPatientRoleId(String id)
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append("select r from Role r left join r.rolePrtcptnsList rp left join rp.participationAct enc left join enc.prtcptnsActList p left join p.roleParticipation role ");
        jpql.append(" where r.codeEtsId=");
        jpql.append(convertInJpql(RoleCode.BED.code().stringValue()));
        jpql.append(" and enc.codeEtsId=");
        jpql.append(convertInJpql(ActCode.INDEPARTMENT.code().stringValue()));
        jpql.append(" and enc.statusCode=");
        jpql.append(convertInJpql(ActStatus.ACTIVE.code().stringValue()));
        jpql.append(" and role.roleId=");
        jpql.append(convertInJpql(id));
        @SuppressWarnings("unchecked")
        List<Role> roles = em.createQuery(jpql.toString()).getResultList();
        if (roles.isEmpty())
        {
            return null;
        }
        else
        {
            return roles.get(0);
        }
    }


    public String getBaseEncounterQueryJpql(Map<String, Map<String, Object>> conditions, Class<?> clazz)
    {
        StringBuilder jpql1 = new StringBuilder();
        if (clazz != null && clazz.equals(Long.class))
        {
            jpql1.append("select count(distinct enc.actId) from PatientEncounter enc");
        }
        else
        {
            jpql1.append("select distinct enc from PatientEncounter enc");
        }
        StringBuilder jpql2 = new StringBuilder();
        jpql2.append(" where 1=1 ");
        // 查询动作及条件
        if (conditions.get("enc") != null)
        {
            if (conditions.get("enc").get("codeEtsId") != null)
            {
                jpql2.append(" and enc.codeEtsId =");
                jpql2.append(convertInJpql(conditions.get("enc").get("codeEtsId")));
            }
            if (conditions.get("enc").get("actId") != null)
            {
                jpql2.append(" and enc.actId =");
                jpql2.append(convertInJpql(conditions.get("enc").get("actId")));
            }
            if (conditions.get("enc").get("statusCode") != null)
            {
                jpql2.append(" and enc.statusCode =");
                jpql2.append(convertInJpql(conditions.get("enc").get("statusCode")));
            }
            if (conditions.get("enc").get("activityStartDateTs") != null)
            {
                jpql2.append(" and enc.activityStartDateTs =:activityStartDateTs");
            }
        }
        // 参与角色条件
        if (conditions.get("p") != null && conditions.get("r") != null)
        {
            jpql1.append(" left join enc.prtcptnsActList p left join p.roleParticipation r ");

            if (conditions.get("r").get("roleId") != null)
            {
                jpql2.append(" and r.roleId =");
                jpql2.append(convertInJpql(conditions.get("r").get("roleId")));
            }

            if (conditions.get("r").get("classCode") != null)
            {
                jpql2.append(" and r.classCode =");
                jpql2.append(convertInJpql(conditions.get("r").get("classCode")));
            }

            if (conditions.get("r").get("codeEtsId") != null)
            {
                jpql2.append(" and r.codeEtsId =");
                jpql2.append(convertInJpql(conditions.get("r").get("codeEtsId")));
            }

            if (conditions.get("p").get("typeCode") != null)
            {
                jpql2.append(" and p.typeCode =");
                jpql2.append(convertInJpql(conditions.get("p").get("typeCode")));
            }

            if (conditions.get("p").get("typeCode<>") != null)
            {
                jpql2.append(" and p.typeCode not in ");
                jpql2.append(convertInJpql(conditions.get("p").get("typeCode<>")));
            }

            if (conditions.get("p").get("sequenceNum") != null)
            {
                String sequenceNum = (String) conditions.get("p").get("sequenceNum");
                if ("1".equals(sequenceNum))
                {
                    jpql2.append(" and ( p.sequenceNum = 1 or p.sequenceNum is null ) ");
                }
                else
                {
                    jpql2.append(" and p.sequenceNum = ");
                    jpql2.append(convertInJpql(conditions.get("p").get("sequenceNum")));
                }
            }

        }
        // 查询动作ii条件
        if (conditions.get("aii") != null)
        {
            jpql1.append(" left join enc.actsIiList aii ");

            if (conditions.get("aii").get("identifierName") != null)
            {
                jpql2.append(" and aii.identifierName=");
                jpql2.append(convertInJpql(conditions.get("aii").get("identifierName")));
            }
            if (conditions.get("aii").get("extensionTxt") != null)
            {
                jpql2.append(" and aii.extensionTxt =");
                jpql2.append(convertInJpql(conditions.get("aii").get("extensionTxt")));
            }
            if (conditions.get("aii").get("clinicNo") != null)
            {
                jpql2.append(" and aii.clinicNo =");
                jpql2.append(convertInJpql(conditions.get("aii").get("clinicNo")));
            }
        }
        // 参与角色ii条件
        if (conditions.get("r") != null && conditions.get("rii") != null)
        {
            jpql1.append(" left join r.roleIiList rii ");

            if (conditions.get("rii").get("identifierName") != null)
            {
                jpql2.append(" and rii.identifierName =");
                jpql2.append(convertInJpql(conditions.get("rii").get("identifierName")));
            }
            if (conditions.get("rii").get("extensionTxt") != null)
            {
                jpql2.append(" and rii.extensionTxt =");
                jpql2.append(convertInJpql(conditions.get("rii").get("extensionTxt")));
            }

        }
        // 关联目标动作条件
        if (conditions.get("ta") != null && conditions.get("sr") != null)
        {
            jpql1.append(" left join enc.sourceActRelationsList sr left join sr.targetAct ta");
            if (conditions.get("sr").get("typeCode") != null)
            {
                jpql2.append(" and sr.typeCode =");
                jpql2.append(convertInJpql(conditions.get("sr").get("typeCode")));
            }

            if (conditions.get("sr").get("splitCode") != null)
            {
                jpql2.append(" and sr.splitCode =");
                jpql2.append(convertInJpql(conditions.get("sr").get("splitCode")));
            }

            if (conditions.get("sr").get("splitCode<>") != null)
            {
                jpql2.append(" and (sr.splitCode <>");
                jpql2.append(convertInJpql(conditions.get("sr").get("splitCode<>")));
                jpql2.append(" or sr.splitCode is null)");
            }
            if (conditions.get("ta").get("classCode") != null)
            {
                jpql2.append(" and ta.classCode=");
                jpql2.append(convertInJpql(conditions.get("ta").get("classCode")));

            }
            if (conditions.get("ta").get("statusCode") != null)
            {
                jpql2.append(" and ta.statusCode in ");
                jpql2.append(convertInJpql(conditions.get("ta").get("statusCode")));

            }
        }

        if (conditions.get("tre is empty") != null)
        {
            jpql2.append(" and enc.targetActRelationsList is empty ");
        }

        if (conditions.get("sre is empty") != null)
        {
            jpql2.append(" and enc.sourceActRelationsList is empty ");
        }

        if (conditions.get("tre") != null)
        {
            jpql1.append(" left join enc.targetActRelationsList tre ");

            if (conditions.get("tre").get("typeCode<>") != null)
            {
                jpql2.append(" and tre.typeCode not in ");
                jpql2.append(convertInJpql(conditions.get("tre").get("typeCode<>")));
            }

        }

        // 关联源动作条件
        if (conditions.get("sa") != null && conditions.get("tre") != null)
        {
            jpql1.append(" left join tre.sourceAct sa");

        }
        // 关联源动作的参与角色条件
        if (conditions.get("sa") != null && conditions.get("p2") != null && conditions.get("r2") != null)
        {
            jpql1.append(" left join sa.prtcptnsActList p2 left join p2.roleParticipation r2 ");
            if (conditions.get("p2").get("typeCode") != null)
            {
                jpql2.append(" and p2.typeCode =");
                jpql2.append(convertInJpql(conditions.get("p2").get("typeCode")));
            }
            if (conditions.get("r2").get("classCode") != null)
            {
                jpql2.append(" and r2.classCode =");
                jpql2.append(convertInJpql(conditions.get("r2").get("classCode")));
            }
            if (conditions.get("r2").get("roleId") != null)
            {
                jpql2.append(" and r2.roleId =");
                jpql2.append(convertInJpql(conditions.get("r2").get("roleId")));
            }
        }
        // 关联源动作的参与角色的范围实体条件
        if (conditions.get("sa") != null && conditions.get("p2") != null && conditions.get("r2") != null && conditions.get("se2") != null)
        {
            jpql1.append(" left join r2.scoperEntities se2");
            if (conditions.get("se2").get("entityId") != null)
            {
                jpql2.append(" and se2.entityId=");
                jpql2.append(convertInJpql(conditions.get("se2").get("entityId")));
            }
        }
        // 关联源动作的参与角色的范围实体的扮演角色条件
        if (conditions.get("sa") != null && conditions.get("p2") != null && conditions.get("r2") != null && conditions.get("se2") != null
                && conditions.get("pr3") != null)
        {
            jpql1.append(" left join se2.playerRolesList pr3");
            if (conditions.get("pr3").get("roleId") != null)
            {
                jpql2.append(" and pr3.roleId=");
                jpql2.append(convertInJpql(conditions.get("pr3").get("roleId")));
            }
        }

        // 参与角色的扮演实体
        if (conditions.get("r") != null && conditions.get("pe") != null)
        {
            jpql1.append(" left join r.playerEntities pe");
        }
        // 参与角色的扮演实体的名称条件
        if (conditions.get("r") != null && conditions.get("pe") != null && conditions.get("en") != null && conditions.get("enu") != null)
        {
            jpql1.append(" left join pe.entyNamesList en");
            jpql1.append(" left join en.entyNameUsesList enu");

            if (conditions.get("en").get("formatted") != null)
            {
                jpql2.append(" and en.formatted=");
                jpql2.append(convertInJpql(conditions.get("en").get("formatted")));
            }
            if (conditions.get("enu").get("use") != null)
            {
                jpql2.append(" and enu.use=");
                jpql2.append(convertInJpql(conditions.get("enu").get("use")));
            }
        }

        // 参与角色的范围实体条件
        if (conditions.get("r") != null && conditions.get("se") != null)
        {
            jpql1.append(" left join r.scoperEntities se");

            if (conditions.get("se").get("entityId") != null)
            {
                jpql2.append(" and se.entityId =");
                jpql2.append(convertInJpql(conditions.get("se").get("entityId")));
            }
        }
        // 参与角色的范围实体所扮演的角色条件
        if (conditions.get("r") != null && conditions.get("se") != null && conditions.get("pr") != null)
        {
            jpql1.append(" left join se.playerRolesList pr");
            if (conditions.get("pr").get("roleId") != null)
            {
                jpql2.append(" and pr.roleId =");
                jpql2.append(convertInJpql(conditions.get("pr").get("roleId")));
            }
        }
        // 参与角色的关联目标角色条件
        if (conditions.get("r") != null && conditions.get("tr") != null && conditions.get("l") != null)
        {
            jpql1.append(" left join r.sourceRoleRimCoreRoleLink l left join l.targetRole tr");
            if ((conditions.get("l").get("typeCode") != null))
            {
                jpql2.append(" and l.typeCode =");
                jpql2.append(convertInJpql(conditions.get("l").get("typeCode")));
            }
            if (conditions.get("tr").get("classCode") != null)
            {
                jpql2.append(" and tr.classCode =");
                jpql2.append(convertInJpql(conditions.get("tr").get("classCode")));
            }
            if (conditions.get("tr").get("roleId") != null)
            {
                jpql2.append(" and tr.roleId =");
                jpql2.append(convertInJpql(conditions.get("tr").get("roleId")));
            }

        }

        // 排序
        if (conditions.get("order by") != null)
        {
            jpql2.append(" order by ");
            if (conditions.get("order by").get("desc") != null)
            {
                jpql2.append(conditions.get("order by").get("desc"));
                jpql2.append(" desc  ");
            }
            else if (conditions.get("order by").get("asc") != null)
            {
                jpql2.append(conditions.get("order by").get("asc"));
                jpql2.append(" asc ");
            }
        }
        String jpql = jpql1.toString() + jpql2.toString();
        log.info("jpql语句为:" + jpql);
        return jpql;
    }

}
